import django_filters
from django_filters.rest_framework import DjangoFilterBackend
from main.filters import NumberInFilter
from main.models import Client, Request
from main.permissions import DjangoModelFullPermissions
from main.views.reqservice import ReqServicesSerializer
from rest_framework import serializers, viewsets


class RequestSerializer(serializers.ModelSerializer):
    client = serializers.PrimaryKeyRelatedField(
        queryset=Client.objects.all(), required=False, allow_null=True
    )
    request_service = ReqServicesSerializer(read_only=True, required=False)
    attachs = serializers.SerializerMethodField(read_only=True, required=False)
    tasks = serializers.SerializerMethodField(read_only=True, required=False)

    def get_tasks(self, obj):
        return obj.tasks.count()

    def get_attachs(self, obj):
        return obj.attachs.count()

    class Meta:
        model = Request
        fields = (
            "id",
            "first_name",
            "phone_number",
            "number_in_program",
            "note",
            "changes_history",
            "status",
            "created_on",
            "updated_on",
            "request_service",
            "client",
            "tasks",
            "attachs",
        )


class RequestsFilter(django_filters.FilterSet):
    ids = NumberInFilter(field_name="id", lookup_expr="in")

    class Meta:
        model = Request
        fields = ("id",)


class RequestViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows Requests to be viewed.
    """

    queryset = Request.objects.all().order_by("status")
    serializer_class = RequestSerializer
    permission_classes = (DjangoModelFullPermissions,)
    filter_backends = [DjangoFilterBackend]
    filterset_class = RequestsFilter
